<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="90%"
    draggable
    @close="closeDialog"
  >
    <!-- <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item>
          <el-button
            class="ml-3"
            @click="
              useDownload(
                '/wms/inventorydifference/export',
                '导出表格名称',
                searchParam
              )
            "
          >
            <template #icon><i-ep-download /></template>导出</el-button
          >
        </el-form-item>
      </el-form>
    </div> -->

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :cell-style="cellStyle"
      >
        <el-table-column
          label="仓库号"
          prop="warehouseCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="仓库名称"
          prop="warehouseName"
          min-width="100"
          show-overflow-tooltip
        />

        <el-table-column
          label="存储区号"
          prop="storageSectionCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="存储区名称"
          prop="storageSectionName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="料架"
          prop="shelfName"
          min-width="120"
          show-overflow-tooltip
        />

        <el-table-column
          label="仓位编号"
          prop="binCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="仓位名称"
          prop="binName"
          min-width="120"
          show-overflow-tooltip
        />

        <el-table-column
          label="存货编码"
          prop="materialCode"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="200"
          show-overflow-tooltip
        />
        <!-- <el-table-column
          label="包装条码"
          prop="storageCode"
          min-width="150"
          show-overflow-tooltip
        /> -->
        <el-table-column
          label="包装编号"
          prop="storageCode"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="存储批次"
          prop="stockBatch"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="供应批次"
          prop="supplyBatch"
          min-width="150"
          show-overflow-tooltip
        />
        <!-- <el-table-column
          label="数量"
          prop="quantity"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="数量单位"
          prop="quantityUnit"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <el-table-column
          label="数据来源"
          prop="inventoryDataSource"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{
              useDictionary(
                "InventoryDataSource",
                scope.row.inventoryDataSource
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="差异类型"
          prop="inventoryDifferenceType"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{
              useDictionary("DifferenceType", scope.row.inventoryDifferenceType)
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="差异数量"
          prop="differenceQuantity"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="是否已平账"
          prop="balanced"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("YesNo", scope.row.balanced) }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="searchParam.inventoryState != 5"
          fixed="right"
          label="操作"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.storageUnitId == null"
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="平账凭证号"
          prop="balanceDocumentCode"
          min-width="120"
          show-overflow-tooltip
        /> -->

        <!-- <el-table-column
          label="备注"
          prop="remarks"
          min-width="300"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              v-if="
                scope.row.inventorydifferenceType == '3' &&
                scope.row.balanced == '0'
              "
              type="primary"
              size="small"
              link
              @click="outbound(scope.row)"
            >
              出库
            </el-button>
            <el-button
              v-if="
                (scope.row.inventorydifferenceType == '2' ||
                  scope.row.inventorydifferenceType == '3' ||
                  scope.row.inventorydifferenceType == '4') &&
                scope.row.balanced == '0'
              "
              type="primary"
              size="small"
              link
              @click="comfirmStatus(scope.row)"
              >已调整</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
      <el-dialog
        :close-on-click-modal="false"
        v-model="confirmStatusVisible"
        title="盘点库存调整"
        width="500"
      >
        <el-form :model="confirmForm">
          <el-form-item label="包装条码" :label-width="120">
            <el-input v-model="confirmForm.storageCode" disabled />
          </el-form-item>
          <el-form-item label="存货编码" :label-width="120">
            <el-input v-model="confirmForm.materialCode" disabled />
          </el-form-item>
          <el-form-item label="物料名称" :label-width="120">
            <el-input v-model="confirmForm.materialName" disabled />
          </el-form-item>
          <el-form-item label="物料凭证编号" :label-width="120">
            <el-input
              v-model="confirmForm.balanceDocumentCode"
              placeholder="请输入物料凭证号"
              :disabled="confirmForm.inventorydifferenceType == '4'"
            />
          </el-form-item>
          <el-form-item label="备注" :label-width="120">
            <el-input
              v-model="confirmForm.remarks"
              type="textarea"
              :rows="3"
              maxlength="255"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelConfirmDialog">取消</el-button>
            <el-button type="primary" @click="confirm"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button v-if="searchParam.inventoryState != 5" type="primary" :loading="loading" @click="confirmData">确
          定</el-button> -->
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <wmsinventorydifference-edit
    :visible="addDialog.visible"
    :title="addDialog.title"
    :data="addDialog.data"
    @reset-table="(id: string) => (getTableList())"
    :is-readonly="addDialog.readvisible"
    @change-visible="changeVisible"
  />
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "WMSinventorydifferenceNEW",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/wms/wmsinventorytaskmaterial/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};
// const visibleDialog = ref(false);
// 初始化搜索参数数据
const searchParamInit = {
  stockBatch: "",
  supplyBatch: "",
  customerId: "",

  organizationId: "",

  plantId: "",

  storageLocationId: "",

  warehouseId: "",

  storageTypeId: "",

  storageSectionId: "",

  binId: "",
  binCode: "",
};

const deleteParam = {
  api: "/wms/inventorydifference/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const confirmForm = reactive({
  id: "",
  materialCode: "",
  materialName: "",
  storageCode: "",
  balanceDocumentCode: "",
  inventorydifferenceType: "",
  remarks: "",
});

const confirmStatusVisible = ref(false);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      // getTableList();
    }
  }
);

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal?.inventoryTaskId) {
      const { inventoryTaskId, inventoryState } = newVal;
      searchParam.value.inventoryTaskId = inventoryTaskId;
      searchParam.value.inventoryState = inventoryState;
      search();
    }
  }
);

/** 重置表单 */
function resetForm() {}

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

const dataTableRef = ref();
async function confirmData() {
  // console.log(
  //   "dataTableRef.value",
  //   dataTableRef.value,
  //   dataTableRef.value.getSelectionRows()
  // );
  // const list = dataTableRef.value.getSelectionRows();
  // emit("select-row", list);

  // visibleDialog.value = false;
  // emit("change-visible", false);
  // resetForm();

  loading.value = true;
  await request({
    url: "/wms/inventorydifference/saveConfirm",
    method: "post",
    data: { inventoryTaskId: props.data.inventoryTaskId },
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`操作成功`);
  closeDialog();
  emit("reset-table", "111");
}

const emit = defineEmits(["reset-table", "change-visible", "select-row"]);
async function outbound(data: any) {
  const res = await request({
    url: "/wms/inventorydifference/outbound",
    method: "post",
    data: {
      id: data.id,
    },
  });
  if (res.code == "200") {
    ElMessage.success(`出库成功！`);
    getTableList();
  }
}

function comfirmStatus(row: any) {
  confirmForm.id = row.id;
  confirmForm.materialCode = row.materialCode;
  confirmForm.materialName = row.materialName;
  confirmForm.storageCode = row.storageCode;
  confirmForm.inventorydifferenceType = row.inventorydifferenceType;
  confirmStatusVisible.value = true;
}

async function confirm() {
  const res = await request({
    url: "/wms/inventorydifference/balance",
    method: "post",
    data: confirmForm,
  });
  if (res.code == "200") {
    ElMessage.success(`调整成功！`);
    cancelConfirmDialog();
    getTableList();
  }
}

function cancelConfirmDialog() {
  confirmForm.id = "";
  confirmForm.materialCode = "";
  confirmForm.materialName = "";
  confirmForm.storageCode = "";
  confirmForm.balanceDocumentCode = "";
  confirmForm.inventorydifferenceType = "";
  confirmForm.remarks = "";
  confirmStatusVisible.value = false;
}
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
/** 打开盘点计划表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    getInfo(roleObj.id);
  }
  addDialog.title = "修改盘点数量";
  addDialog.readvisible = false;
  addDialog.visible = true;
}
// 查询详情
async function getInfo(id: string) {
  const { data } = await request({
    url: `/wms/inventorydifference/get/${id}`,
    method: "get",
  });
  addDialog.data = data;
}
function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

const cellStyle = (data) => {
  if (data.row.balanced === 0) {
    return {
      color: "#000",
      background: "#FBE2E2",
      fontWeight: 700,
    };
  } else {
    return {
      color: "#000",
      background: "#AFE564",
      fontWeight: 700,
    };
  }
};

function formatName(outCode: string) {
  return outCode.split("Q")[0];
}
</script>
